package pub.tbc.api.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.helper.HttpResponseHelper;
import pub.tbc.api.service.mapping.ServiceMapping;
import pub.tbc.api.service.mapping.ServiceMappingProvider;
import pub.tbc.toolkit.Objs;

/**
 * @author tbc on 2017/3/1 16:43:44.
 */
@Slf4j
public abstract class AbstractHttpInboundHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    protected ServiceMapping serviceMapping = ServiceMappingProvider.getServiceParse();


    /**
     * 判断解码是否成功
     *
     * @param context ChannelHandlerContext
     * @param request FullHttpRequest
     * @throws Exception
     */
    protected void checkDecoderResult(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
        if (Objs.isEmpty(request)) {
            HttpResponseHelper.badRequest(context, "");
            return;
        }

        if (!request.decoderResult().isSuccess()) {
            HttpResponseHelper.badRequest(context, "");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
        log.error("发生异常： {}", cause.getMessage());
        context.close();
        context.fireChannelRead(cause);
    }


}
